import { useState } from "react";
import {
	getInfoGoodsSpu,
	getInfoGoodsSku,
	getGoodsSkuLogList,
	batchUpdateStatusGoodsSpu,
	batchUpdateStatusGoodsSku,
	batchRemoveDefaultMatchOp,
	setRunningVolumeSku,
	enableSyncGoodsSpu,
	enableSyncGoodsSku,
	removeGoodsSkuMatch,
	setDefaultGoodsSkuMatch,
	changeGoodsSkuMatch
} from "./service";
import { message, Modal } from "antd";
import { getCurrentUser } from "@/utils/authority";
import { batchUpdateGoodsSkuInfo } from "./service";

export default fn => {
	const [dialog, setDialog] = useState();
	const [modalProps, setModalProps] = useState({});

	const refresh = () => {
		setTimeout(() => {
			fn.current && fn.current();
		}, 500);
	};

	/** 弹窗枚举 */
	const DialogEnum = {
		// 从店铺导入商品
		ShopImportModal: "ShopImportModal",
		// Excel导入款信息
		ExcelImportModal: "ExcelImportModal",
		// 从Excel导入商品
		ExcelImportProductsModal: "ExcelImportProductsModal",
		// 批量修改商品
		BatchModifyProductsModal: "BatchModifyProductsModal",
		// 库存同步到店铺
		InventorySynchronizationModal: "InventorySynchronizationModal",
		// 新增/编辑商品
		SpuViewModel: "SpuViewModel",
		// 商品备注
		SkuRemarkModal: "SkuRemarkModal",
		// 查看历史成本价
		HistoryPriceModal: "HistoryPriceModal",
		// 未匹配供应商商品
		UnmatchedSupplierProductsModal: "UnmatchedSupplierProductsModal",
		// 批量删除商品资料
		BatchDeleteGoodsModal: "BatchDeleteGoodsModal",
		// 检测无用商
		CheckGoodsModal: "CheckGoodsModal",
		// 修改价格
		UpdateSkuPriceModal: "UpdateSkuPriceModal",
		// 设置默认跑量商品
		SetDefaultRunningVolumeSkuModal: "SetDefaultRunningVolumeSkuModal",
		// 设置合格证
		SetCertificateOfConformityModal: "SetCertificateOfConformityModal",
		// 批量编辑spu商品信息
		BatchEditSpuModal: "BatchEditSpuModal",
		// 查看日志
		SelectLogModal: "SelectLogModal",
		// 编辑sku商品信息
		EditSkuModal: "EditSkuModal",
		// 商品匹配
		GoodsMatchDrawer: "GoodsMatchDrawer",
		// 导出组件
		ActionExportExcelModal: "ActionExportExcelModal",
		// 同步库存
		StockSyncModal: "StockSyncModal",
		// 退货去向
		ReturnDestinationModal: "ReturnDestinationModal",
		// 自动生成系统商品规则
		AutomaticGenerateSetModal: "AutomaticGenerateSetModal",
		// 商品信息同步更新
		ProductSynchronizationUpdateModal: "ProductSynchronizationUpdateModal",
		//过滤更新商品
		FilterUpdateGoods: 'FilterUpdateGoods',
		//自动生成设置
		EncodeSetting: 'EncodeSetting',
		//自动生成设置
		CancelMatch: 'CancelMatch',
	};
	// 操作事件
	const handle = {
		add: () => {
			setModalProps({
				// 关闭事件
				onCancel
			});
			setDialog(DialogEnum.SpuViewModel);
		},
		// 复制
		copy: record => {
			getInfoGoodsSpu({ id: record.id }).then(res => {
				const { success, data } = res;
				// 复制需要删除id
				delete data.id;
				if (success) {
					// 设置弹窗入参
					setModalProps({
						// 详情
						details: data,
						// 关闭事件
						onCancel
					});
					setDialog(DialogEnum.SpuViewModel);
				}
			});
		},
		// 批量修改状态
		batchUpdateStatus: ({ isSkuType, ids, status }, callBack) => {
			if (ids.length === 0) {
				message.warning("请勾选商品");
				return;
			}
			isSkuType
				? batchUpdateStatusGoodsSku({ ids, status }).then(res => {
					const { success, msg } = res;
					if (success) {
						message.success(msg);
						callBack();
					}
				})
				: batchUpdateStatusGoodsSpu({ ids, status }).then(res => {
					const { success, msg } = res;
					if (success) {
						message.success(msg);
						callBack();
					}
				});
		},
		// 编辑
		edit: (record, isSkuType) => {
			isSkuType
				? getInfoGoodsSku({ id: record.id }).then(res => {
					const { success, data } = res;
					if (success) {
						// 设置弹窗入参
						setModalProps({
							// 详情
							details: data,
							// 关闭事件
							onCancel
						});
						setDialog(DialogEnum.EditSkuModal);
					}
				})
				: getInfoGoodsSpu({ id: record.id }).then(res => {
					const { success, data } = res;
					if (success) {
						// 设置弹窗入参
						setModalProps({
							// 详情
							details: data,
							// 关闭事件
							onCancel
						});
						setDialog(DialogEnum.SpuViewModel);
					}
				});
		},
		// 启/禁用同步库存
		setSyncInventoryGoods: ({ syncStatus, ids, isSkuType }) => {
			if (ids.length === 0) {
				message.warning("请勾选商品");
				return;
			}

			setModalProps({
				ids,
				isSkuType,
				// 同步库存状态1启用，0禁用
				syncStatus,
				// 关闭事件
				onCancel
			});
			setDialog(DialogEnum.StockSyncModal);
		},
		// 批量修改sku商品信息
		batchUpdateGoodsSkuInfo: ({ ids, tabsType }) => {
			if (ids.length === 0) {
				message.warning("请勾选商品");
				return;
			}
			setModalProps({
				tabsType,
				// 关闭事件
				onCancel
			});
			setDialog(DialogEnum.BatchModifyProductsModal);
		},
		// 批量修改spu商品信息
		batchUpdateSpu(ids) {
			if (ids.length === 0) {
				message.warning("请勾选商品");
				return;
			}
			setDialog(DialogEnum.BatchEditSpuModal);
		},
		// 修改价格
		updateSkuPrice: (selectedRows, data, isSkuType) => {
			console.log('updateSkuPrice', selectedRows, data, isSkuType)
			console.log(isSkuType, 'ddddd')

			if (selectedRows.length === 0) {
				message.warning("请勾选商品");
				return;
			}
			// 判断是否包含非供应商匹配商品：matchOrNot = 0
			// some返回一个boolean值
			// matchType 1-供应商匹配， 2精准匹配
			// 有默认匹配的供应商才能改价
			const skuList = []; //按款式改价sku集合

			if (isSkuType) { //sku
				if (
					selectedRows.some(item => item.matchOrNot == 0 || item.matchType == 2) ||
					selectedRows.filter(item => item?.goodsSkuMatches?.some(e => e.isDefault == 1)).length === 0
				) {
					message.warning("请选择默认供应商匹配的商品");
					return;
				}
			} else { //按款式
				if (selectedRows.length) {
					selectedRows.forEach(item => {
						if (item.skuList.length) {
							item.skuList.forEach(z => {
								if (z.isUpdatePrice) {
									skuList.push(z.id)
								}
							})
						}
					})
					if (skuList.length == 0) {
						message.warning("所选款式无可以改价的sku");
						return;
					}
				} else {
					message.warning("请选择商品");
					return;
				}
			}
			setModalProps({
				...data,
				selectedRows: selectedRows,
				isSkuType,
				skuList
			});
			setDialog(DialogEnum.UpdateSkuPriceModal);
		},
		// 设为默认跑量商品
		setDefaultRunningVolume: selectedRows => {
			if (selectedRows.length === 0) {
				message.warning("请勾选商品");
				return;
			}
			if (selectedRows.length != 1) {
				message.warning("默认跑量商品仅可设置一个");
				return;
			}
			if (selectedRows[0].runningVolumeStatus == 2) {
				message.warning("默认跑量商品无需再次设置");
				return;
			}
			if (selectedRows[0].runningVolumeStatus != 1) {
				message.warning("请选择一个跑量商品");
				return;
			}
			setDialog(DialogEnum.SetDefaultRunningVolumeSkuModal);
		},
		// 设置合格证
		setQualifiedProve: selectedRows => {
			// 至少选择一个商品，点击设置合格证后，滑出弹框，针对勾选的商品进行编辑，下拉项的取值为合格证模板配置页面的已有配置项，修改后覆盖原商品已有或未有的合格证模板（一期是默认写死的一个合格证）
			if (selectedRows.length === 0) {
				message.warning("请勾选商品");
				return;
			}
			setModalProps({ selectedRows })
			setDialog(DialogEnum.SetCertificateOfConformityModal);
		},
		// 查看历史成本价/查看历史采购价
		historyPrice: (title, record) => {
			setModalProps({
				title,
				// 关闭事件
				record,
				onCancel
			});
			setDialog(DialogEnum.HistoryPriceModal);
		},
		// 查看日志
		setSelectLog({ logType }) {
			setModalProps({
				logType,
				// 关闭事件
				onCancel
			});
			setDialog(DialogEnum.SelectLogModal);
		},
		// 匹配
		matchGoods: arg => {
			setModalProps({
				...arg,
				// 关闭事件
				refresh,
				onCancel
			});
			setDialog(DialogEnum.GoodsMatchDrawer);
		},
		// 退货去向
		returnDirection: ({ selectedRows }) => {
			if (selectedRows?.length === 0) {
				message.warning("请勾选商品");
				return;
			}
			setModalProps({
				selectedRows,
				// 关闭事件
				onCancel
			});
			setDialog(DialogEnum.ReturnDestinationModal);
		},
		// 过滤更新商品
		filterGoods: ({ selectedRows, form }) => {
			const searchData = form.getFieldsValue();
			setModalProps({
				selectedRows,
				// 关闭事件
				onCancel,
				searchData,
				refresh
			});
			setDialog(DialogEnum.FilterUpdateGoods);
		},
		//解除匹配
		batchCancelMatch: ({ operaType, ids, isSkuType, formData }) => {
			if (operaType == 1) {
				//针对勾选的数据
				if (ids.length === 0) {
					return message.warning("请勾选商品");
				}
			} else {
				if (Object.keys(formData).filter(v => (formData[v] || formData[v] === 0) && !['pageSize', 'pageNum', 'type', 'total'].includes(v)).length == 0) {
					return message.warning("请先筛选商品");
				}
			}
			setModalProps({
				ids,
				isSkuType,
				formData,
				operaType: operaType,
				onCancel
			});
			setDialog(DialogEnum.CancelMatch);
		},
		// 导出
		export({ text, isSkuType, selectedKeys, form, pagination, imgType }) {
			const searchData = form.getFieldsValue();
			// 判断是否有筛选项
			let isSearch = Object.values(searchData).some(value => value !== null);
			// 判断是否有筛选项
			// 勾选>筛选>无筛选
			const businessKey = selectedKeys.length ? 3 : isSearch ? 2 : 1;
			const condition = {
				[isSkuType ? "skuIds" : "spuIds"]: selectedKeys,
				[isSkuType ? "skuParam" : "spuParam"]: searchData
			};
			// 图片类型 0 表示未显示图片 1 显示图片
			if (imgType) condition.spuParam.type = imgType;
			// taskType: isSkuType ? 3004 : 3005,
			const createTaskData = {
				businessParam: JSON.stringify({
					businessKey,
					...condition,
					// current: pagination.current, // 当前页
					// size: pagination.pageSize, // 每页的数量
					uuid: getCurrentUser().uuid
				})
			};
			switch (text) {
				case "导出款式信息（图）":
					createTaskData.taskType = 3008;
					setModalProps({
						createTaskData,
						// 关闭事件
						onCancel
					});
					setDialog(DialogEnum.ActionExportExcelModal);
					break;
				case "导出款式信息":
					createTaskData.taskType = 3005;
					setModalProps({
						createTaskData,
						// 关闭事件
						onCancel
					});
					setDialog(DialogEnum.ActionExportExcelModal);
					break;
				case "导出商品资料":
					createTaskData.taskType = 3004;
					setModalProps({
						createTaskData,
						// 关闭事件
						onCancel
					});
					setDialog(DialogEnum.ActionExportExcelModal);
					break;
				case "导出历史成本价":
					createTaskData.taskType = 3006;
					setModalProps({
						createTaskData,
						// 关闭事件
						onCancel
					});
					setDialog(DialogEnum.ActionExportExcelModal);
					break;
				case "导出历史采购价":
					createTaskData.taskType = 3007;
					setModalProps({
						createTaskData,
						// 关闭事件
						onCancel
					});
					setDialog(DialogEnum.ActionExportExcelModal);
					break;
				default:
					break;
			}
		},
		removeMatch: id => {
			console.log("removeMatch", id);
			removeGoodsSkuMatch({ id }).then(({ success, data, msg }) => {
				if (success) {
					message.success(msg || "解除匹配成功");
					refresh();
				} else {
					message.warning(msg || "解除匹配失败");
				}
			});
		},
		setDefaultMatch: id => {
			console.log("setDefaultMatch", id);
			setDefaultGoodsSkuMatch({ id }).then(({ success, data, msg }) => {
				if (success) {
					message.success(msg || "设置默认匹配成功");
					refresh();
				} else {
					message.warning(msg || "设置默认匹配失败");
				}
			});
		},
		changeMatch: (item, id) => {
			const API_DATA = {
				id: id,
				matchType: 2,
				// "supplierCode": "",
				supplierId: item.storeId,
				supplierName: item.storeName,
				// "supplierSkuCode": "",
				supplierSkuId: item.goodsId,
				supplierSkuImage: item.goodsName,
				supplierSkuName: item.goodsName,

				supplierSkuPrice: item.vipPrice || item.goodsPrice,
				supplierSkuSpecs: item.color + ";" + item.size,
				supplierSpuCode: item.goodsCommonid
			};
			changeGoodsSkuMatch(API_DATA).then(res => {
				if (res.success) {
					message.success(message.msg || "操作成功");
					refresh();
				} else {
					message.warning(message.msg || "操作失败");
				}
			});
		},
		// 列表保存
		saveEditRow(dataSource, fetchList, { successFn, failFn }) {
			const API_DATA = dataSource.find(e => e.isEdit);
			console.log("API_DATA", API_DATA);

			if (API_DATA && this.checkEditRow(API_DATA)) {
				// 调用接口修改sku信息
				batchUpdateGoodsSkuInfo({ ...API_DATA, ids: [API_DATA.id] })
					.then(res => {
						const { msg, success } = res;
						successFn && successFn(res);
						if (success) {
							message.success(msg);
							onCancel();
							fetchList();
						} else {
							failFn && failFn();
						}
					})
					.catch(err => {
						console.log("err", err);
					});
			}
		},
		// 校验数据能否保存
		checkEditRow(data) {
			if (!data) return true;
			// 校验商品名称和成本价是否有值
			if (!data.skuName) {
				message.warning("请输入商品名称");
				return false;
			}
			if (!data.costPrice) {
				message.warning("请输入成本价");
				return false;
			}
			return true;
		}
	};
	// 关闭弹窗
	function onCancel() {
		setDialog(null);
	}

	return {
		/** 弹窗 */
		dialog,
		setDialog,
		// 弹窗枚举
		DialogEnum,
		// 弹窗参数
		modalProps,
		// 操作事件对象
		handle,
		onCancel,
		refresh
	};
};
